package com.kuangshen.string;

import java.util.*;

public class StringDemo {
    public static void main(String[] args) {
        // String StringBuffer StringBuilder的区别
        // 可变性
        // 线程安全性
        // 性能
        String s1 = "abc";
        String s = new String("abc");
        s += "111";
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("111");
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("222");

        // == 和 equals
        String a = new String("abc");
        String b = new String("abc");
        String aa = "abc";
        String bb = "abc";
        System.out.println(aa==bb);
        System.out.println(a==b);
        System.out.println(a.equals(b));
        System.out.println(aa.equals(bb));
        HashSet<String> objects = new HashSet<>();
        objects.add(a);

        // hashcode() 和 equals 的联系
        // 1. 不会创建“类对应的散列表”
        Person p1 = new Person(100, "aaa");
        Person p2 = new Person(100, "aaa");
        Person p3 = new Person(200, "eee");
        System.out.printf("%s, %d, %d\n", p1.equals(p2), p1.hashCode(), p2.hashCode());
        System.out.printf("%s, %d, %d\n", p2.equals(p3), p2.hashCode(), p3.hashCode());
        // 2. 会创建“类对应的散列表”
        Set<Person> personSet = new HashSet<>();
        personSet.add(p1);
        personSet.add(p2);
        personSet.add(p3);
        System.out.println(personSet);

        Map<Person, String> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put(p1, "aaa");
        objectObjectHashMap.put(p2, "aaa");
        objectObjectHashMap.put(p3, "ccc");

        System.out.println(objectObjectHashMap.get(new Person(100, "aaa")));

        // 包装类型的缓存机制
        Integer integer = Integer.valueOf(1);
        System.out.println(integer);

        Character c = '1';
        System.out.println(c);

    }

    private static class Person {
        int age;
        String name;

        public Person(int age, String name) {
            this.age = age;
            this.name = name;
        }

        @Override
        public String toString() {
            return "Person{" +
                    "age=" + age +
                    ", name='" + name + '\'' +
                    '}';
        }

        public boolean equals(Object obj){
            if(obj == null){
                return false;
            }
            if(this == obj){
                return true;
            }
            if(this.getClass() != obj.getClass()){
                return false;
            }
            Person person = (Person) obj;
            return name.equals(person.name) && age == person.age;
        }

//        @Override
//        public int hashCode() {
//            return Objects.hash(age, name);
//        }
    }

}
